package org.water.garden.msn.activity;

import org.water.garden.msn.service.IMsnService;
import org.water.garden.msn.service.MsnServiceConstants;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.provider.Im;
import android.provider.Im.Messages;
import android.util.Log;

/**
 * @author sshwsfc@gmail.com Send MSN message
 */
public class SendMessage extends Activity {

    private static final String LOG_TAG = "SendMsgReceiver";

	IMsnService MsnService;
	ContentValues cvs;
	ContentResolver contentResolver;
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		if(getIntent().hasExtra(Messages.CONTENT_ITEM_TYPE)){
			cvs = (ContentValues)getIntent().getParcelableExtra(Messages.CONTENT_ITEM_TYPE);			
			bindService((new Intent()).setComponent(MsnServiceConstants.MSN_SERVICE_COMPONENT), mConnection, 0);
		}else{
			Log.e(LOG_TAG, "There isn't message content values for send.");
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(mConnection);
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			MsnService = IMsnService.Stub.asInterface(service);
			try {
				MsnService.sendText(cvs.getAsInteger(Messages.ACCOUNT), cvs.getAsString(Messages.CONTACT), cvs.getAsString(Messages.BODY));
				getContentResolver().insert(Im.Messages.CONTENT_URI, cvs );
				
				setResult(RESULT_OK);
			} catch (DeadObjectException ex) {
				Log.e(LOG_TAG, "caught " + ex);
				
				setResult(RESULT_CANCELED);
			} finally {
				finish();
			}
		}

		public void onServiceDisconnected(ComponentName className) {
		}
	};
}
